﻿#if NETCOREAPP3_0
using System.Buffers;
using System.Buffers.Text;

namespace System.Text.Json.Serialization
{
    /// <summary>
    /// 转换 String 类型数据为 Number 数据
    /// </summary>
    public class StringToNumberConverter : JsonConverter<int>
    {
        /// <summary>
        /// 读取方法
        /// </summary>
        /// <param name="reader"></param>
        /// <param name="typeToConvert"></param>
        /// <param name="options"></param>
        /// <returns></returns>
        public override int Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            if (reader.TokenType == JsonTokenType.String)
            {
                var span = reader.HasValueSequence ? reader.ValueSequence.ToArray() : reader.ValueSpan;
                if (Utf8Parser.TryParse(span, out int num, out int bytesConsumed) && span.Length == bytesConsumed)
                    return num;

                if (int.TryParse(reader.GetString(), out num)) return num;
            }
            return reader.GetInt32();
        }

        /// <summary>
        /// 写入方法
        /// </summary>
        /// <param name="writer"></param>
        /// <param name="value"></param>
        /// <param name="options"></param>
        public override void Write(Utf8JsonWriter writer, int value, JsonSerializerOptions options)
        {
            writer.WriteNumberValue(value);
        }
    }
}
#endif
